package org.aplikator.server.data;

import com.google.common.base.Preconditions;
import org.aplikator.client.shared.data.PrimaryKey;
import org.aplikator.client.shared.data.Record;
import org.aplikator.server.descriptor.Collection;
import org.aplikator.server.descriptor.Entity;
import org.aplikator.server.descriptor.Property;

import java.io.Serializable;
import java.util.UUID;


public class RecordUtils {

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T getValue(Record record, Property<T> prop){
        return ((T) record.getValue(prop.getId()));
    }

    public static <T extends Serializable> void setValue(Record record, Property<T> prop, T value) {
        prop.setValue(record, value);
    }
    
    
    public static Record newRecord(Entity entity){
        return new Record(new PrimaryKey(entity.getId(), UUID.randomUUID().toString()));
    }

    public static Record newSubrecord(PrimaryKey ownerPrimaryKey, Collection<?> ownerProperty){
        Preconditions.checkArgument(ownerProperty.getEntity().getId().equals(ownerPrimaryKey.getEntityId()), "Nonequal owner entity:"+ownerProperty.getEntity().getId()+" "+ownerPrimaryKey.getEntityId());
        Record retval = newRecord(ownerProperty.referredEntity);
        retval.setOwnerPropertyId(ownerProperty.getId());
        retval.setOwnerPrimaryKey(ownerPrimaryKey);
        return retval;
    }

}
